package com.example.jf.jfapp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.example.jf.jfapp.LoginActivity;
import com.example.jf.jfapp.R;
import com.example.jf.jfapp.adapter.NearUserListAdapter;
import com.example.jf.jfapp.bean.bean.NearUserListbean;
import com.example.jf.jfapp.bean.request.NearUserListRequest;
import com.example.jf.jfapp.bean.request.NearUserRequest;
import com.example.jf.jfapp.bean.response.NearUserResponse;
import com.example.jf.jfapp.bean.response.NearuserListResponse;
import com.example.jf.jfapp.utils.AppConfigUtils;
import com.example.jf.jfapp.utils.BaiDuLocationUtils;
import com.example.jf.jfapp.utils.Constant;
import com.example.jf.jfapp.utils.RequestUtils;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by jf on 2017/7/29.
 */

public class NearUserListActivity extends AppCompatActivity {
    NearUserListAdapter nadapter;
    private static final String TAG = "NearUserListActivity";
    public static final String USER_LIST_KEY = "USER_LIST_KEY";
ArrayList<NearUserListRequest>nlists=new ArrayList<>();

    ArrayList<NearUserResponse.ResultBean> mResultBeen = new ArrayList<>();

    double mLatitude;
    double mLongitude;
    private NearUserListAdapter listAdapter;
    private String userId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base_list);
        initData();
        RecyclerView rv=(RecyclerView)findViewById(R.id.rl);
        LinearLayoutManager manager=new LinearLayoutManager(this);
        rv.setLayoutManager(manager);
        nadapter=new NearUserListAdapter(nlists);
        rv.setAdapter(nadapter);
        //开启定位，并且点移动到指定的位置

        BaiDuLocationUtils.create(this, new BaiDuLocationUtils.OnLocationListener() {
            @Override
            public void onLocationSucced(BDLocation bdLocation, double latitude, double longitude) {
                mLatitude = latitude;
                mLongitude = longitude;
                Log.e(TAG, "定位成功啦，接受到定位数据" + latitude + "  " + longitude);
                // 构造定位数据
                MyLocationData locData = new MyLocationData
                        .Builder()
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .accuracy(bdLocation.getRadius())
                        .direction(0)
                        .latitude(bdLocation.getLatitude())
                        .longitude(bdLocation.getLongitude())
                        .build();


                LatLng ll = new LatLng(bdLocation.getLatitude(),
                        bdLocation.getLongitude());

                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);


                getNearUser(bdLocation);
            }
        });
    }

    public void initData() {
        getAdapter();
        ArrayList<NearUserResponse.ResultBean> resultBeen = getIntent().getParcelableArrayListExtra(USER_LIST_KEY);

        mLatitude = getIntent().getDoubleExtra("mLatitude",0);
        mLongitude = getIntent().getDoubleExtra("mLongitude",0);

        mResultBeen.addAll(resultBeen);
        userId = AppConfigUtils.getInstance().getLoginInfo(this).getObjectId();
        if ("".equals(userId)) {
            startActivity(new Intent(NearUserListActivity.this, LoginActivity.class));
        }
        getList(userId,10,0,"");
    }

    public void getNearUser(BDLocation location) {
        //什么时候去请求数据？  定位成功
        OkHttpClient okHttpClient = new OkHttpClient();

        NearUserRequest nearUserRequest = new NearUserRequest(location.getLatitude(), location.getLongitude());

        final Request request = RequestUtils.requestPOST(nearUserRequest, Constant.URL.GETNEARUSER);
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String reuslt = response.body().string();
                Log.i(TAG, "onResponse: " + reuslt);
                NearUserResponse nearUserResponse = new Gson().fromJson(reuslt, NearUserResponse.class);

            }
        });


    }
    public void  getList(String userId,int limit,int timestamp,String otherUserName){
        OkHttpClient okHttpClient = new OkHttpClient();

        NearUserListbean nearUserRequest = new NearUserListbean
                (userId,limit,timestamp,otherUserName);
        String json=new Gson().toJson(nearUserRequest);
        MediaType JSONTYPE = MediaType.parse("application/json;charset=utf-8");
        RequestBody body = RequestBody.create(JSONTYPE, json);
        //final Request request = RequestUtils.requestPOST(nearUserRequest, Constant.URL.GETNEARUSER);
        Request request=new Request.Builder()
                .addHeader("X-LC-Id", "S5KdTtqGDUwpImMvQ6HAJYaL-gzGzoHsz")
                .addHeader("X-LC-Key", "NRPgCGiGxjbtGN2Bn0mlglrL")
                .addHeader("Content-Type", "application/json")
                .url(Constant.URL.GETNEARUSER)
                .post(body)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String reuslt = response.body().string();
                Log.e(TAG, "onResponse: 附近的用户" + reuslt);
                NearuserListResponse nearUserResponse = new Gson().fromJson(reuslt, NearuserListResponse.class);
                for (int i=0;i<nearUserResponse.getResult().size();i++){
                    NearUserListRequest request1=new NearUserListRequest(
                            nearUserResponse.getResult().get(i).getAddress(),
                            nearUserResponse.getResult().get(i).isFolloweeStatus(),
                            nearUserResponse.getResult().get(i).getHeadProtrait(),
                            nearUserResponse.getResult().get(i).getSignature(),
                            nearUserResponse.getResult().get(i).getUserId(),
                            nearUserResponse.getResult().get(i).getUsername()
                    );
                    nlists.add(request1);
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        nadapter.notifyDataSetChanged();

                    }
                });

            }
        });



    }


    public RecyclerView.Adapter getAdapter() {
        listAdapter = new NearUserListAdapter(nlists);
        return listAdapter;
    }

}
